package kz.kstu.aecdemo.desktop.ui.dialog;

import kz.kstu.aec.Authenticator;
import kz.kstu.aec.model.ClientData;
import kz.kstu.aec.model.Point2D;
import kz.kstu.aecdemo.app.delegate.api.AccountDelegate;
import kz.kstu.aecdemo.app.delegate.impl.AccountDelegateImpl;
import kz.kstu.aecdemo.business.util.StringUtil;
import kz.kstu.aecdemo.desktop.util.GUIUtils;

import javax.security.auth.login.AccountException;
import javax.swing.*;
import java.awt.event.*;

public class RegisterDialog extends JDialog {

    private static final String TITLE = "Регистрация";

    private static final int WIDTH = 320;
    private static final int HEIGHT = 200;

    private static final String LOGIN_EXISTS = "Указанный логин уже используется в системе";
    private static final String LOGIN_INCORRECT = "Логин некорректен";
    private static final String PASSWORD_INCORRECT = "Пароль некорректен";
    private static final String PASSWORDS_NOT_MATCH = "Введенные пароли не совпадают";
    private static final String REGISTRATION_SUCCESSFULLY_COMPLIED = "Регистрация успешно завершена";

    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField loginField;
    private JPasswordField passwordField;
    private JPasswordField confirmPasswordField;

    public RegisterDialog() {
    }

    public void initStaticComponents() {
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);
        setSize(WIDTH, HEIGHT);
        setTitle(TITLE);
        initListeners();
        GUIUtils.centerAndShow(this);
    }

    private void initListeners() {

        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        contentPane.registerKeyboardAction(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        onCancel();
                    }
                }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    private void onOK() {
        String login = loginField.getText();
        if (!validateLogin(login)) {
            JOptionPane.showMessageDialog(this, LOGIN_INCORRECT, TITLE, JOptionPane.ERROR_MESSAGE);
            return;
        }

        String password = new String(passwordField.getPassword());
        String confirmedPassword = new String(confirmPasswordField.getPassword());
        if (!password.equals(confirmedPassword)) {
            JOptionPane.showMessageDialog(this, PASSWORDS_NOT_MATCH, TITLE, JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (!validatePassword(password)) {
            JOptionPane.showMessageDialog(this, PASSWORD_INCORRECT, TITLE, JOptionPane.ERROR_MESSAGE);
            return;
        }

        try {
            ClientData clientData = new ClientData(login, password);
            Authenticator authenticator = Authenticator.getInstance();
            Point2D publicKey = authenticator.getPublicKey(clientData);
            AccountDelegate accountDelegate = new AccountDelegateImpl();
            accountDelegate.register(login, publicKey);
            JOptionPane.showMessageDialog(this, REGISTRATION_SUCCESSFULLY_COMPLIED, TITLE, JOptionPane.INFORMATION_MESSAGE);
            dispose();
        } catch (AccountException e) {
            JOptionPane.showMessageDialog(this, LOGIN_EXISTS, TITLE, JOptionPane.ERROR_MESSAGE);
        }
    }

    private void onCancel() {
        dispose();
    }

    private boolean validatePassword(String password) {
        return !StringUtil.isEmptyString(password);
    }

    private boolean validateLogin(String login) {
        return !StringUtil.isEmptyString(login);
    }
}
